﻿import { _decorator, Component, Node, AudioClip, EventTouch, NodeEventType } from 'cc';
import { SysBase } from '../base/SysBase';
import { SysMgr } from '../common/SysMgr';
import { TimeSys } from './TimeSys';
import { SyncFunctor } from '../common/SyncFunctor';
import { Functor } from '../common/Functor';
const { ccclass, property } = _decorator;

@ccclass('SyncSys')
export class SyncSys extends SysBase {


    funcList = []
    onceFuncMap = new Map<Function,any>();

    onLoad() {
        SysMgr.getSys(TimeSys).addLoop(this);
    }

    addOnceSyncFunctor(functor, arg) {
        this.onceFuncMap[functor] = {
            functor: functor,
            arg: arg
        }
    }

    addSyncFunctor(functor, arg = null) {
        this.funcList.push({
            functor: functor,
            arg: arg
        });
    }

    async loop(dt) {
        let lst = this.funcList

        this.funcList = []
      
        for (let i = 0, len = lst.length; i < len; i++) {
            let data = lst[i]
            if (typeof data.arg[Symbol.iterator] === 'function') 
                await data.functor(...data.arg)
            else
                await data.functor(data.arg)
        }

        let map = this.onceFuncMap
        let keyList = map.keys()
        for (let key of keyList) {
            let data = map.get(key)
            if (typeof data.arg[Symbol.iterator] === 'function')
                await data.functor(...data.arg)
            else
                await data.functor(data.arg)

        }
        this.onceFuncMap.clear()
    }


}

